package StudyCode.summary.mycollection;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class RenormalizesTheArraySoThatItsL2NormIs1 {
	public static void main(String[] argv) {
		double[] v = new double[]{34.45, 35.45, 36.67, 37.78, 37.0000,
				37.1234, 67.2344, 68.34534, 69.87700};
		System.out.println(java.util.Arrays.toString(normalize(v)));
	}

	public static double[] normalize(double[] v) {
		return (scalarMultiply(1.0 / norm(v), v));
	}

	public static double[] scalarMultiply(double a, double[] v) {
		double[] ans = new double[v.length];
		for (int k = 0; k < v.length; k++) {
			ans[k] = a * v[k];
		}
		return (ans);
	}

	public static double[] scalarMultiply(double a, int[] v) {
		double[] ans = new double[v.length];
		for (int k = 0; k < v.length; k++) {
			ans[k] = v[k] * a;
		}
		return (ans);
	}

	public static double norm(double[] data) {
		return (Math.sqrt(sumSquares(data)));
	}

	public static double norm(int[] data) {
		return (Math.sqrt(sumSquares(data)));
	}

	public static double sumSquares(double[] data) {
		double ans = 0.0;
		for (int k = 0; k < data.length; k++) {
			ans += data[k] * data[k];
		}
		return (ans);
	}

	public static double sumSquares(double[][] data) {
		double ans = 0.0;
		for (int k = 0; k < data.length; k++) {
			for (int l = 0; l < data[k].length; l++) {
				ans += data[k][l] * data[k][l];
			}
		}
		return (ans);
	}

	public static int sumSquares(int[] data) {
		int ans = 0;
		for (int k = 0; k < data.length; k++) {
			ans += data[k] * data[k];
		}
		return (ans);
	}

	public static int sumSquares(int[][] data) {
		int ans = 0;
		for (int k = 0; k < data.length; k++) {
			for (int l = 0; l < data[k].length; l++) {
				ans += data[k][l] * data[k][l];
			}
		}
		return (ans);
	}
}
